//
//  CardSelectViewController.m
//  Guazi
//
//  Created by koolearn on 11-6-29.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CardSelectViewController.h"
#import "Card.h"
#import "GuaziAppDelegate.h"
#import "CardCell.h"


@implementation CardSelectViewController


@synthesize message;


#pragma mark - init & destroy

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        cards = nil;
        selectedIndex = -1;
    }
    return self;
}

- (void)dealloc
{
    [cards release];
    [message release];
    [super dealloc];
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


#pragma mark - 加载数据

- (NSArray*) loadCards
{
    NSArray* userCards = [Card cardsForUser:[GuaziAppDelegate getAppDelegate].user.userId];
    return userCards;
}


#pragma mark - 操作方法s

- (void) done
{
    if ( selectedIndex == -1 ) {
        [GuaziAppDelegate showAlert:@"请选择发送给用户的名片"];
        return;
    }
    
    Card* card = [cards objectAtIndex:selectedIndex];
    NSString* askId = [message askId];
    BOOL result = [TwitterClient acceptAskCardSync:askId dmId:message.messageId cardId:card.cardId];
    if ( !result ) {
        [GuaziAppDelegate showAlert:@"抱歉，给用户发送名片失败"];
    }
    else {
        message.appendResult = kDMResultCardAccept;
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void) cancel
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - View lifecycle

- (void) buildBarButtonItems
{
    UIBarButtonItem* rightButton = [[UIBarButtonItem alloc] initWithTitle:@"确定" 
                                                                    style:UIBarButtonItemStyleDone 
                                                                   target:self action:@selector(done)];
    self.navigationItem.rightBarButtonItem = rightButton;
    [rightButton release];
    
    UIBarButtonItem* leftButton = [[UIBarButtonItem alloc] initWithTitle:@"放弃" 
                                                                    style:UIBarButtonItemStylePlain 
                                                                   target:self action:@selector(cancel)];
    self.navigationItem.leftBarButtonItem = leftButton;
    [leftButton release];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    cards = [self loadCards];
    [cards retain];
    [self buildBarButtonItems];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [cards release];
    self.message = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [cards count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    Card* card = [cards objectAtIndex:indexPath.row];
    
    CardCell *cell = (CardCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[CardCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    [cell setCard:card];
    return cell;
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (NSString*) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{
    return @"请选择您要发送的名片:";
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ( selectedIndex == indexPath.row ) {
        UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryNone;
        selectedIndex  = -1;
    }
    else {
        if ( selectedIndex >= 0 ) {
            UITableViewCell* cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:selectedIndex inSection:0]];
            if ( cell ) {
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
        }
        
        selectedIndex = indexPath.row;
        
        UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
